#include <rtthread.h>
#include "./Indicate.h"
#include "./Modbus/RTU/Master/modbusrtu_master.h"

static void main_thread(void *parameter);

static struct rt_thread _thread;
ALIGN(RT_ALIGN_SIZE)
static char _thread_stack[512];

static struct rt_event _event;
static unsigned short music_index = 0;
static unsigned short output_flag = 0;
static unsigned short alarm_enum = 0;
static char slave_addr = 0;

void Indicate_Init(char addr)
{
    rt_err_t rt_result;
    slave_addr = addr;
    rt_event_init(&_event, "indicate event", RT_IPC_FLAG_PRIO);
    Alarm_Set(Alarm_IDLE);
    Music_Set(0);
    Move_Over_Output(0);
    rt_result = rt_thread_init(&_thread, "indicate thread", main_thread, RT_NULL, _thread_stack, sizeof(_thread_stack), 10, 2);
    if (rt_result == RT_EOK)
    {
        rt_thread_startup(&_thread); /* 启动线程 */
    }
    else
    {
        rt_kprintf("indicate thread error\n");
    }
}

void main_thread(void *parameter)
{
    rt_uint32_t event_value;
    Modbus_Error_Code mb_result;
    while (1)
    {
        rt_event_recv(&_event, 1 << 0, RT_EVENT_FLAG_CLEAR | RT_EVENT_FLAG_OR, RT_WAITING_FOREVER, &event_value);
        if (event_value & (1 << 0))
        {
            mb_result = MR_Writer_Holding_Register(slave_addr, 0x0011, alarm_enum, 100); /* 设置警示灯 */
            if (Modbus_Master_OK != mb_result)
            {
                rt_event_send(&_event, 1 << 0);
            }
        }
        if (event_value & (1 << 1))
        {
            mb_result = MR_Writer_Holding_Register(slave_addr, 0x0010, music_index, 100); /* 设置音乐 */
            if (Modbus_Master_OK != mb_result)
            {
                rt_event_send(&_event, 1 << 1);
            }
        }
        if (event_value & (1 << 2))
        {
            mb_result = MR_Writer_Holding_Register(slave_addr, 0x0012, output_flag, 100); /* 设置输出 */
            if (Modbus_Master_OK != mb_result)
            {
                rt_event_send(&_event, 1 << 2);
            }
        }
    }
}

void Alarm_Set(enum Alarm alarm)
{
    alarm_enum = (unsigned short)alarm;
    rt_event_send(&_event, 1 << 0);
}

void Music_Set(char index)
{
    music_index = index;
    rt_event_send(&_event, 1 << 1);
}

void Move_Over_Output(char _flag)
{
    output_flag = _flag;
    rt_event_send(&_event, 1 << 2);
}
